using System.IO;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Blob;

namespace DailyPoetryX.AzureStorage.Services.Implementations {
    /// <summary>
    /// 收藏存储。
    /// </summary>
    public class BlobFavoriteStorage : IFavoriteStorage {
        /******** 公开变量 ********/

        /******** 私有变量 ********/

        /// <summary>
        /// 容器名。
        /// </summary>
        private const string ContainerName = "favorite-storage";

        /// <summary>
        /// 容器。
        /// </summary>
        private CloudBlobContainer _container;

        /******** 继承方法 ********/
        /// <summary>
        /// 保存收藏数据。
        /// </summary>
        /// <param name="favoriteBytes">收藏数据。</param>
        /// <param name="name">用户名。</param>
        public async Task SaveAsync(byte[] favoriteBytes, string name) {
            var blob = _container.GetBlockBlobReference(name + ".zip");
            await blob.UploadFromByteArrayAsync(favoriteBytes, 0,
                favoriteBytes.Length);
        }

        /// <summary>
        /// 读取收藏数据。
        /// </summary>
        /// <param name="name">用户名。</param>
        public async Task<byte[]> GetAsync(string name) {
            var blob = _container.GetBlockBlobReference(name + ".zip");
            if (!await blob.ExistsAsync()) {
                return null;
            }

            var memoryStream = new MemoryStream();
            await blob.DownloadToStreamAsync(memoryStream);
            return memoryStream.ToArray();
        }

        /******** 公开方法 ********/

        /// <summary>
        /// 收藏存储。
        /// </summary>
        /// <param name="accountProvider">Azure存储账户提供者。</param>
        public BlobFavoriteStorage(IAzureStorageAccountProvider accountProvider) {
            var blobClient =
                accountProvider.GetAccount().CreateCloudBlobClient();
            _container = blobClient.GetContainerReference(ContainerName);
        }

        /******** 私有方法 ********/
    }
}